<?php

namespace App\Console\Commands;

use App\Models\Handroom;
use App\Models\Home\Property;
use App\Models\HousePrice;
use App\Models\Rentalhouse;
use Illuminate\Console\Command;

class CalculateAverage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'calculateAverage:calAverage';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '计算平均房价';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 新房
        $new = Property::where('status','T')->get(['region','regionname','average'])->groupBy('region');
        collect($new)->map(function ($item){
            $sum = $item->sum('average');
            $count = $item->count();
            $average = (int)($sum/$count);
            $month = (int)date('m');
            $map['average'] = $average;
            $map['region_id'] = $item[0]['region'];
            $map['region_name'] = $item[0]['regionname'];
            $map['month'] = $month;
            $map['count'] = $count;
            $map['type'] = 'newhouse';
            HousePrice::create($map);
        });
        //二手房
        $hand = Handroom::where('status','T')->get(['region','regionname','average'])->groupBy('region');
        collect($hand)->map(function ($item){
            $hsum = $item->sum('average');
            $hcount = $item->count();
            $hmonth = (int)date('m');
            $haverage = (int)($hsum/$hcount);
            $hmap['average'] = $haverage;
            $hmap['region_id'] = $item[0]['region'];
            $hmap['region_name'] = $item[0]['regionname'];
            $hmap['month'] = $hmonth;
            $hmap['count'] = $hcount;
            $hmap['type'] = 'hand';
            HousePrice::create($hmap);
        });
        //出租房
        $rental = Rentalhouse::where('status','T')->get(['region','regionname','price'])->groupBy('region');
        collect($rental)->map(function ($item){
            $rsum = $item->sum('price');
            $rcount = $item->count();
            $rmonth = (int)date('m');
            $raverage = (int)($rsum/$rcount);
            $rmap['average'] = $raverage;
            $rmap['region_id'] = $item[0]['region'];
            $rmap['region_name'] = $item[0]['regionname'];
            $rmap['month'] = $rmonth;
            $rmap['count'] = $rcount;
            $rmap['type'] = 'rental';
            HousePrice::create($rmap);
        });
    }
}
